/* eslint-disable @typescript-eslint/no-explicit-any */
import { getCurrentLocationInfo } from './client';
import { qqnews } from './ua';
import axios from 'axios';
import { loadjs } from './util';
const mapkey = 'ZTCBZ-M6FWU-DFTVG-2HCU2-OM7SV-2LBCF';

// 获取当前用户地理定位
export const getUserLocal = () => new Promise((resolve) => {
  if (navigator.geolocation) {
    try {
      navigator.geolocation.getCurrentPosition((position: any) => {
        resolve(position);
      });
    } catch (error) {
      resolve({});
    }
  } else {
    resolve({});
  }
});

// 通过坐标，计算坐标点的地址信息
export const geoCoder = (local: Record<string, any>) => new Promise((resolve) => {
  const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${local.lat},${local.lng}&key=${mapkey}`;
  axios.get(url).then((res) => {
    resolve(res.data.result);
  });
});

export const getULocal = () => new Promise((resolve) => {
  if (qqnews) {
    // 在客户端内，采用客户端定位jsapi
    getCurrentLocationInfo().then((res: any) => {
      // currentLocationInfo:
      // adCode: "110108"
      // address: "北京市海淀区西北旺东路10号院西区9号楼"
      // city: "北京"
      // district: "海淀区"
      // latitude: 40.039899
      // longitude: 116.274282
      // name: "腾讯北京总部大楼"
      // province: "北京"
      // qnAdCode: "110000"
      if (res.currentLocationInfo?.adCode) {
        const id = res.currentLocationInfo.adCode;
        const obj = {
          ad_info: {
            adcode: id,
          },
        };
        resolve(obj);
      }
    });
  } else {
    loadjs('https://map.qq.com/api/gljs?v=1.exp&key=ZTCBZ-M6FWU-DFTVG-2HCU2-OM7SV-2LBCF', () => {
      // 客户端外，使用腾讯地图api
      getUserLocal().then((location: any) => {
        const lat = location.coords.latitude;
        const lng = location.coords.longitude;
        geoCoder({ lat, lng }).then((res: any) => {
          // ad_info:
          // adcode: "110108"
          // city: "北京市"
          // city_code: "156110000"
          // district: "海淀区"
          // location: {lat: 40.045132, lng: 116.375}
          // name: "中国,北京市,北京市,海淀区"
          // nation: "中国"
          // nation_code: "156"
          // province: "北京市"
          resolve(res);
        });
      });
    });
  }
});
export default {
  getULocal,
};
